package com.happyfamily.springboot.crowdsourcingplatform.controller.pan;

import com.happyfamily.springboot.crowdsourcingplatform.annotation.OperationLogDetail;
import com.happyfamily.springboot.crowdsourcingplatform.base.result.PageTableRequest;
import com.happyfamily.springboot.crowdsourcingplatform.base.result.Results;
import com.happyfamily.springboot.crowdsourcingplatform.enums.OperationType;
import com.happyfamily.springboot.crowdsourcingplatform.enums.OperationUnit;
import com.happyfamily.springboot.crowdsourcingplatform.model.Orders;
import com.happyfamily.springboot.crowdsourcingplatform.model.Work;
import com.happyfamily.springboot.crowdsourcingplatform.service.guo.FrontNeedService;
import com.happyfamily.springboot.crowdsourcingplatform.service.pan.OrderService;
import com.happyfamily.springboot.crowdsourcingplatform.service.pan.PurchaseService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author Administrator
 * @create 2020/02/23 01:01
 */
@Controller
@Slf4j
@RequestMapping("api-front/purchase")
public class PurchaseController
{

	@Autowired
	private PurchaseService purchaseService;

	@Autowired
	private FrontNeedService frontNeedService;


	@Autowired
	private OrderService orderService;

	@GetMapping("/list")
	@ResponseBody
	@ApiOperation(value = "作品数据获取", notes = "查询类型是已通过审核", httpMethod = "GET", response = Results.class)
	@OperationLogDetail(detail = "作品数据获取", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public Results<Work> getAllNeedsByPage(PageTableRequest request)
	{
		request.countOffset();
		return purchaseService.getAllWorksByPage(request.getOffset(), request.getLimit());
	}



	/**
	 * 跳转到作品详情页面
	 * @param model
	 * @param work
	 * @return
	 */
	@GetMapping("/details")
	public String userDetail(Model model, Work work)
	{
		model.addAttribute("work", purchaseService.getWorkById(work.getWid()));
		return "frontPage/workdetails";
	}


	/**
	 * 文件下载作品购买
	 * @param wid
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@GetMapping("/download")
	@ApiOperation(value = "文件下载", notes = "查询类型是作品id", httpMethod = "GET", response = Results.class)
	@OperationLogDetail(detail = "文件下载", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public Results download(String wid, HttpServletResponse response, HttpServletRequest request,ModelAndView model) throws IOException
	{

		SecurityContextImpl securityContext = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account1 = securityContext.getAuthentication().getName();

		//根据上传的作品id查询作品标题
		Work work = purchaseService.getWorkById(Integer.valueOf(wid));
		//设置下载文件的名字+类型
		String filename=work.getFname();
			//获取发布者的账号
		String account=work.getWuseraccount();

			if (work != null)
			{
				//设置文件路径

				String fileDirPath = new String("src/main/resources/doc/" +account+"/"+filename);

				File file = new File(fileDirPath);

				if (file.exists())
				{


					response.reset();
					// 设置强制下载不打开
//					response.setContentType("application/force-download");

					//避免中文乱码
					response.setHeader("Connection", "close");
					//设置传输的类型
					response.setHeader("Content-Type", "application/octet-stream");
					response.setHeader("Content-Transfer-Encoding", "chunked");
					response.setHeader("Access-Control-Allow-Origin", "*");
					response.setHeader("Content-Disposition", "attachment;fileName=" + new String(filename.getBytes("utf-8"), "ISO-8859-1"));
					response.setContentType("application/OCTET-STREAM");


					byte[] buffer = new byte[1024];
					FileInputStream fis = null;
					BufferedInputStream bis = null;
					try
					{
						fis = new FileInputStream(file);
						bis = new BufferedInputStream(fis);
						OutputStream os = response.getOutputStream();
						int i = bis.read(buffer);
						while (i != -1)
						{
							os.write(buffer, 0, i);

							i = bis.read(buffer);
						}


						bis.close();

						return null;


					} catch (Exception e)
					{
						e.printStackTrace();
					} finally
					{
						if (bis != null)
						{
						}
						if (fis != null)
						{
							try
							{
								fis.close();
							} catch (IOException e)
							{
								e.printStackTrace();
							}
						}

					}
				}
			}else{

				return null;
			}
           return null;
	}


	@GetMapping("/place")
	@ApiOperation(value = "个人订单数据获取", notes = "查询类型是用户账号", httpMethod = "GET", response = ModelAndView.class)
	@OperationLogDetail(detail = "个人订单数据获取", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public ModelAndView placeAnOrder(String wid, ModelAndView modelAndView ,HttpServletRequest request)
	{
		System.out.println(wid);

		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");

		//获得你登录的账号
		String account = securityContextImpl.getAuthentication().getName();


		//根据作品id修改作品数据为已购买
		purchaseService.updateWork(wid,account);

		//生成购买作品的订单
		orderService.addOrder(wid,account);

         //根据作品id查询订单id
		Integer oid=purchaseService.getOrdesById(wid);

		//将oid插入order_form
		orderService.addOrderForm(oid);


		modelAndView.setViewName("/frontPage/list-order-work");

		return modelAndView;
	}





}
